package Presentacion.academico;

import global.Iconos;
import javax.swing.DefaultListModel;

public class dlgAsignacionPeriodoCurso extends javax.swing.JDialog {

    private DefaultListModel modelocurso;
    private DefaultListModel modeloasignado;
    private Iconos ico = new Iconos();

    /**
     * Creates new form dlgAsignacionCursoPeriodo
     *
     * @param parent
     * @param modal
     */
    public dlgAsignacionPeriodoCurso(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        setTitle("ASIGNACIÓN DE CURSOS AL PERIODO");
        setResizable(false);
        iconos();
        setLocationRelativeTo(this);
        iniciar();
    }
    
    private void iconos() {
        btnnuevo.setIcon(ico.getNuevo());
        btnguardar.setIcon(ico.getGuardar());
        btnsalir.setIcon(ico.getSalir());
        btnactualizar.setIcon(ico.getActualizar());
    }

    private void iniciar() {
        visiblidad(true);
        btnactualizar.setEnabled(false);
        btnguardar.setEnabled(false);
        frmConsultaPeriodoCurso.objperiodoCurso.periodo.listarPeriodoCombo(cboperiodo);
        limpiarModelos();
    }

    private void limpiarModelos() {
        modeloasignado = new DefaultListModel();
        modelocurso = new DefaultListModel();
        lCurso.setModel(modelocurso);
        lCursoasignado.setModel(modeloasignado);
    }

    public void visiblidad(boolean visibilidad) {
        if (visibilidad != true) {
            btnactualizar.setVisible(true);
            btnguardar.setVisible(false);
        } else {
            btnactualizar.setVisible(false);
            btnguardar.setVisible(true);
        }
    }

    private boolean guardarAsignacion() {
        int total = modeloasignado.size();
        int t = modelocurso.size();
        int s = 0;

        for (int j = 0; j < t; j++) {
            lCurso.setSelectedIndex(j);
            if (frmConsultaPeriodoCurso.objperiodoCurso.ExistenciaAsignacionCurso(lCurso.getSelectedValue().toString(),
                    cboperiodo.getSelectedItem().toString()) == true) {
                frmConsultaPeriodoCurso.objperiodoCurso.EliminarCursosAsignados(lCurso.getSelectedValue().toString(), cboperiodo.getSelectedItem().toString());
            }
        }

        for (int i = 0; i < total; i++) {
            lCursoasignado.setSelectedIndex(i);
            if (frmConsultaPeriodoCurso.objperiodoCurso.ExistenciaAsignacionCurso(lCursoasignado.getSelectedValue().toString(),
                    cboperiodo.getSelectedItem().toString()) == false) {
                frmConsultaPeriodoCurso.objperiodoCurso.sacarIdCurso(lCursoasignado.getSelectedValue().toString());
                frmConsultaPeriodoCurso.objperiodoCurso.periodo.sacarIdPeriodo(cboperiodo.getSelectedItem().toString());
                if (frmConsultaPeriodoCurso.objperiodoCurso.guardarAsignacionCurso() == false) {
                    s++;
                }
            }
        }
        if (s == 0) {
            frmConsultaPeriodoCurso.generartabla();
            return true;
        } else {
            return false;
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        panelCurso = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        lCurso = new javax.swing.JList();
        jScrollPane2 = new javax.swing.JScrollPane();
        lCursoasignado = new javax.swing.JList();
        btnpasartodo = new javax.swing.JButton();
        btnpasar = new javax.swing.JButton();
        btnregresar = new javax.swing.JButton();
        btnregresartodo = new javax.swing.JButton();
        cboperiodo = new javax.swing.JComboBox();
        jToolBar4 = new javax.swing.JToolBar();
        btnnuevo = new javax.swing.JButton();
        btnguardar = new javax.swing.JButton();
        btnactualizar = new javax.swing.JButton();
        btnsalir = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        panelCurso.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jScrollPane1.setViewportView(lCurso);

        jScrollPane2.setViewportView(lCursoasignado);

        btnpasartodo.setText(">>");
        btnpasartodo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnpasartodoActionPerformed(evt);
            }
        });

        btnpasar.setText(">");
        btnpasar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnpasarActionPerformed(evt);
            }
        });

        btnregresar.setText("<");
        btnregresar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnregresarActionPerformed(evt);
            }
        });

        btnregresartodo.setText("<<");
        btnregresartodo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnregresartodoActionPerformed(evt);
            }
        });

        cboperiodo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        cboperiodo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cboperiodoActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout panelCursoLayout = new javax.swing.GroupLayout(panelCurso);
        panelCurso.setLayout(panelCursoLayout);
        panelCursoLayout.setHorizontalGroup(
            panelCursoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelCursoLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelCursoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(cboperiodo, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 355, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(panelCursoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(btnregresar, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnregresartodo, javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnpasar, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnpasartodo, javax.swing.GroupLayout.Alignment.LEADING))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 397, Short.MAX_VALUE)
                .addContainerGap())
        );
        panelCursoLayout.setVerticalGroup(
            panelCursoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelCursoLayout.createSequentialGroup()
                .addGap(9, 9, 9)
                .addComponent(cboperiodo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(panelCursoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2)
                    .addComponent(jScrollPane1))
                .addContainerGap())
            .addGroup(panelCursoLayout.createSequentialGroup()
                .addGap(114, 114, 114)
                .addComponent(btnpasartodo)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnpasar)
                .addGap(11, 11, 11)
                .addComponent(btnregresar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnregresartodo)
                .addContainerGap(255, Short.MAX_VALUE))
        );

        jToolBar4.setBorder(null);
        jToolBar4.setFloatable(false);
        jToolBar4.setBorderPainted(false);

        btnnuevo.setText("Nuevo");
        btnnuevo.setFocusable(false);
        btnnuevo.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnnuevo.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnnuevo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnnuevoActionPerformed(evt);
            }
        });
        jToolBar4.add(btnnuevo);

        btnguardar.setText("Guardar");
        btnguardar.setFocusable(false);
        btnguardar.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnguardar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnguardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnguardarActionPerformed(evt);
            }
        });
        jToolBar4.add(btnguardar);

        btnactualizar.setText("Actualizar");
        btnactualizar.setFocusable(false);
        btnactualizar.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnactualizar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnactualizar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnactualizarActionPerformed(evt);
            }
        });
        jToolBar4.add(btnactualizar);

        btnsalir.setText("Salir");
        btnsalir.setFocusable(false);
        btnsalir.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnsalir.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnsalir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnsalirActionPerformed(evt);
            }
        });
        jToolBar4.add(btnsalir);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jToolBar4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(panelCurso, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jToolBar4, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(panelCurso, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnpasartodoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnpasartodoActionPerformed
        int j = modelocurso.size();
        if (modelocurso.isEmpty() != true) {
            for (int i = 0; i < j; i++) {
                modeloasignado.addElement(lCurso.getSelectedValue());
                lCursoasignado.setModel(modeloasignado);
                modelocurso.removeElementAt(lCurso.getSelectedIndex());
                lCurso.setSelectedIndex(0);
                lCursoasignado.setSelectedIndex(0);
            }
        } else {
            global.Mensajes.mostrarMensaje("Cursos", "No hay cursos para asignar", 3);
        }
    }//GEN-LAST:event_btnpasartodoActionPerformed

    private void btnpasarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnpasarActionPerformed
        if (modelocurso.isEmpty() != true) {
            modeloasignado.addElement(lCurso.getSelectedValue());
            lCursoasignado.setModel(modeloasignado);
            modelocurso.removeElementAt(lCurso.getSelectedIndex());
            lCurso.setSelectedIndex(0);
            lCursoasignado.setSelectedIndex(0);
        } else {
            global.Mensajes.mostrarMensaje("Cursos", "No hay cursos para asignar", 3);
        }
    }//GEN-LAST:event_btnpasarActionPerformed

    private void btnregresarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnregresarActionPerformed
        if (modeloasignado.isEmpty() != true) {
            if (frmConsultaPeriodoCurso.objperiodoCurso.QuitarCurso(lCursoasignado.getSelectedValue().toString(),
                    cboperiodo.getSelectedItem().toString()) == true) {
                modelocurso.addElement(lCursoasignado.getSelectedValue());
                lCurso.setModel(modelocurso);
                modeloasignado.removeElementAt(lCursoasignado.getSelectedIndex());
                lCurso.setSelectedIndex(0);
                lCursoasignado.setSelectedIndex(0);
            }
        } else {
            global.Mensajes.mostrarMensaje("Cursos", "No hay cursos asignado", 3);
        }
    }//GEN-LAST:event_btnregresarActionPerformed

    private void btnregresartodoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnregresartodoActionPerformed
        int j = modeloasignado.size();
        if (modeloasignado.isEmpty() != true) {
            for (int i = 0; i < j; i++) {
                if (frmConsultaPeriodoCurso.objperiodoCurso.QuitarCurso(lCursoasignado.getSelectedValue().toString(),
                        cboperiodo.getSelectedItem().toString()) == true) {
                    modelocurso.addElement(lCursoasignado.getSelectedValue());
                    lCurso.setModel(modelocurso);
                    modeloasignado.removeElementAt(lCursoasignado.getSelectedIndex());
                    lCurso.setSelectedIndex(0);
                    lCursoasignado.setSelectedIndex(0);
                } else {
                    return;
                }
            }
        } else {
            global.Mensajes.mostrarMensaje("Cursos", "No hay cursos asignado", 3);
        }
    }//GEN-LAST:event_btnregresartodoActionPerformed

    private void btnnuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnnuevoActionPerformed
        iniciar();
        visiblidad(true);
    }//GEN-LAST:event_btnnuevoActionPerformed

    private void btnguardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnguardarActionPerformed
        if (guardarAsignacion() == true) {
            global.Dialogos.GuardadoconExito();
            iniciar();
        } else {
            global.Dialogos.Error("Error al asignar los cursos");
        }

    }//GEN-LAST:event_btnguardarActionPerformed

    private void btnactualizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnactualizarActionPerformed
        if (guardarAsignacion() == true) {
            global.Mensajes.mostrarMensaje("Correcto!", "Datos actualizados correctamente...!", 1);
            dispose();
            iniciar();
        } else {
            global.Dialogos.Error("Error al actualizar los datos");
        }

    }//GEN-LAST:event_btnactualizarActionPerformed

    private void btnsalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnsalirActionPerformed
        dispose();
        iniciar();
    }//GEN-LAST:event_btnsalirActionPerformed

    private void cboperiodoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cboperiodoActionPerformed
        if (cboperiodo.getSelectedIndex() != 0 && cboperiodo.getSelectedIndex() != -1) {
            btnactualizar.setEnabled(true);
            btnguardar.setEnabled(true);
            limpiarModelos();
            frmConsultaPeriodoCurso.objperiodoCurso.CursoAsignados(lCursoasignado, modeloasignado, cboperiodo.getSelectedItem().toString());
            frmConsultaPeriodoCurso.objperiodoCurso.CursoNoAsignados(lCurso, modelocurso, cboperiodo.getSelectedItem().toString());
        }
    }//GEN-LAST:event_cboperiodoActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(dlgAsignacionPeriodoCurso.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(dlgAsignacionPeriodoCurso.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(dlgAsignacionPeriodoCurso.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(dlgAsignacionPeriodoCurso.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                dlgAsignacionPeriodoCurso dialog = new dlgAsignacionPeriodoCurso(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnactualizar;
    private javax.swing.JButton btnguardar;
    private javax.swing.JButton btnnuevo;
    private javax.swing.JButton btnpasar;
    private javax.swing.JButton btnpasartodo;
    private javax.swing.JButton btnregresar;
    private javax.swing.JButton btnregresartodo;
    private javax.swing.JButton btnsalir;
    public javax.swing.JComboBox cboperiodo;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JToolBar jToolBar4;
    private javax.swing.JList lCurso;
    private javax.swing.JList lCursoasignado;
    private javax.swing.JPanel panelCurso;
    // End of variables declaration//GEN-END:variables
}
